package cn.edu.hizee.gps.util;

import cn.edu.hizee.gps.dao.ContactRepository;
import cn.edu.hizee.gps.dao.Site2Repository;
import cn.edu.hizee.gps.dao.SiteRepository;
import cn.edu.hizee.gps.dao.UserRepository;
import cn.edu.hizee.gps.model.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ZX
 */
@Service
public class TimeUtil {


    @Autowired
    private Site2Repository site2Repository;

    @Autowired
    private ContactRepository contactRepository;

    @Autowired
    private UserRepository userRepository;


    /**
     * 倒计时+flag修改
     * @param limitSec
     * @throws InterruptedException
     */
    public void Time(int limitSec, String id, PositionInfo positionInfo) throws InterruptedException{
        int min = limitSec;
        int i = 0;
        while(limitSec > 0){
            System.out.println("limitSec " + limitSec);
            if(positionInfo != null) {
                if (positionInfo.getFlag().equals("1")) {
                    System.out.println("flag=1");
                    break;
                } else if (positionInfo.getFlag().equals("0")) {
                    i++;
                }
            }else {
                return;
            }
            --limitSec;
            TimeUnit.SECONDS.sleep(1);
        }
        if(i == min){
            // 向联系人推送危险信息
            //
            //
//            pushDX(id);
            int lngSize = positionInfo.getLng().size() - 1;
            int latSize = positionInfo.getLat().size() - 1;
            List<Site2> list = new ArrayList<>();
            Site2 site2 = new Site2();
            if(lngSize > 0 && latSize > 0) {
                site2.setUserId(Integer.valueOf(id));
                site2.setLng(positionInfo.getLng().get(lngSize));
                site2.setLat(positionInfo.getLat().get(latSize));
            }else {
                site2.setUserId(Integer.valueOf(id));
            }
            System.out.println(site2Repository.countSite2sByUserId(Integer.valueOf(id)));
            if(site2Repository.countSite2sByUserId(Integer.valueOf(id)) == 0) {
                site2Repository.save(site2);
            }else {
                if(lngSize > 0 && latSize > 0) {
                    site2Repository.updateSite2(Integer.valueOf(id), positionInfo.getLng().get(lngSize), positionInfo.getLat().get(latSize));
                }else {
                    return;
                }
            }
        }
    }

    /**
     * 危险短信构建
     * @param userId
     */
    public void pushDX(String userId) throws IOException {
        System.out.println(userId);
        String destMobiles = "";
        String content = "";
        List<Contact> list = contactRepository.findContact(Integer.valueOf(userId));
        List<User> users = userRepository.findAllById(Integer.valueOf(userId));
        if(list.size() == 1){
            destMobiles += list.get(0).getContactPhone();
        }else if(list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                if(i != list.size() - 1) {
                    destMobiles += list.get(i).getContactPhone() + ",";
                }else {
                    destMobiles += list.get(i).getContactPhone();
                }
            }
        }
        content += "【安安互助】：安安互助提醒您，您保护的" + users.get(0).getRealName() + "遇到危险，请立即打开安安互助APP实施救援";
        httpDX(content, destMobiles);
    }

    /**
     * 验证码短信构建
     * @param phone
     */
    public String pushYZM(String phone) throws IOException {
        String yzm = String.valueOf((int)((Math.random()*9+1)*1000));
        String content = "【安安互助】:您的安安互助登陆验证码为：" + yzm;
        httpDX(content, phone);
        return yzm;
    }

    /**
     * 短信发送
     */
    public static void httpDX(String content, String destMobiles) throws IOException {
        // 发送短信地址，以下为示例地址，具体地址询问网关获取
        String url_send_sms = "http://117.48.217.182:8860/sendSms";
        // 用户账号，必填
        String cust_code = "240150";
        // 用户密码，必填
        String cust_pwd = "M1DEBOND9N";
        // 短信内容，必填
//        String content = "【安安互助】验证码1234";
        // 接收号码，必填，同时发送给多个号码时,号码之间用英文半角逗号分隔
//        String destMobiles = "17857349530";
        // 业务标识，选填，由客户自行填写不超过20位的数字
        String uid = "";
        // 长号码，选填
        String sp_code = "";
        // 是否需要状态报告
        String need_report = "yes";
        // 数字签名，签名内容根据 “短信内容+客户密码”进行MD5编码后获得
        String sign = content + cust_pwd;
        sign = getMD5(sign.getBytes("UTF-8"));
        String json_send_sms = "{\"cust_code\":\"" + cust_code + "\",\"sp_code\":\"" + sp_code + "\",\"content\":\"" + content +
                "\",\"destMobiles\":\"" + destMobiles + "\",\"uid\":\"" + uid + "\",\"need_report\":\"" + need_report + "\",\"sign\":\"" + sign + "\"}";
        URL url = new URL(url_send_sms);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream out = httpURLConnection.getOutputStream();
        out.write(json_send_sms.getBytes("UTF-8"));
        System.out.println("send msg:\t"+json_send_sms);
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            System.out.println("recv msg:\t"+resultBuffer.toString());
        } catch (Exception e) {
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            httpURLConnection.disconnect();
        }
    }

    /**
     * MD5加密
     * @param source
     * @return
     */
    public static String getMD5(byte[] source) {
        String s = null;
        char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f' };
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

}
